/**
 * Constants for the GRIDSTER configuration
 */
var GRIDSTER_MARGIN_LEFT = 6;
var GRIDSTER_MARGIN_RIGHT = 6;
var GRIDSTER_WIDTH = 64;
var GRIDSTER_HEIGHT = 64;
var GRIDSTER_MIN_COLS = 1;
var GRIDSTER_MAX_COLS = 25;
var GRIDSTER_MAX_ROWS = 30;
var GRIDSTER_RESIZE = true;

var listComponent = [];

var dashboardId = "";
var dashboardName = "";

var gridster;

var GridsterUtil = function() {
    return {
        newGridster : function () {
            listComponent = [];
            if (undefined !== gridster) {
                /* gridster document: 
                    Destroy this gridster by removing any sign of its presence, 
                    making it easy to avoid memory leaks. 
                    If 'true' to remove gridster from DOM */
                //gridster.destroy(true);
                //console.log('destroy');
                gridster.remove_all_widgets(function(){
                    console.log('all widgets removed');
                });
            } else {
                gridster = $(".gridster > ul").gridster({
                    widget_margins: [GRIDSTER_MARGIN_LEFT, GRIDSTER_MARGIN_RIGHT], 
                    widget_base_dimensions: [GRIDSTER_WIDTH, GRIDSTER_HEIGHT],
                    min_cols: GRIDSTER_MIN_COLS,
                    max_cols: GRIDSTER_MAX_COLS,
                    resize: {
                        enabled: GRIDSTER_RESIZE,
                        start: function (e, ui, widget) {
                            console.log("start resize");
                        },
                        stop: function (e, ui, widget) {
//                            var newHeight = this.resize_coords.data.height;
//                            var newWidth = this.resize_coords.data.width;
//                            console.log("new height" + newHeight);
//                            console.log("new width" + newWidth);
//                            router.currentView.updateProfile();
                            var containerId = widget[0]['id'];
//                            var component = GridsterUtil.getComponentByContainerId(containerId);
//                            if(component != undefined) {
//                                if(LiveViewUtil.isWidgetTypeLineChart(component)
//                                        || LiveViewUtil.isWidgetTypeColumnChart(component)
//                                        || LiveViewUtil.isWidgetTypePieChart(component)
//                                        || LiveViewUtil.isWidgetTypeSolidGauge(component)
//                                        || LiveViewUtil.isWidgetTypeAngularGauge(component)) {
//                                    // re-init line chart
//                                    component.initChart();
//                                }
//                            }
                        }
                    },
                    draggable: {
                        stop: function(event, ui){ 
                            event.preventDefault();
//                            router.currentView.updateProfile();
                        }
                    }
                }).data('gridster');
            }
        },
        addContainerMenu : function (containerId) {
            var content = "<div id=\"componentMenu\" class=\"tools menu-container menu-block\">";
                    content += "<a href='javascript:;' onclick=\"return configContainer(" + containerId + ", this);\" class=\"remove\">";
//                        content += "<i class=\"fa fa-gears\"></i>";
                        content += "<i>" + IconUtil.getConfigureDashboard() + "</i>";
                    content += "</a>";
                    content += "<span> </span>";
                    content += "<a href='javascript:removeContainer(" + containerId + ");' class=\"remove\">";
//                        content += "<i class=\"fa fa-times-circle\"></i>";
                        content += "<i>" + IconUtil.getCloseDashboard() + "</i>";
                    content += "</a>";
                content += "</div>  ";
            $('#' + containerId).append(content);
            return false;
        },
        randomInt : function(min, max){
            return Math.floor(Math.random() * (max - min + 1) + min);
        },
        generateUniqueId : function() {
//            var id = new Date().getTime();
//            if($("#"+id).length > 0) {
//                id = new Date().getTime();
//            }
//            if($("#"+id).length > 0) {
//                id = new Date().getTime();
//            }
            var id = GridsterUtil.randomInt(1000000, 9999999);
            if ($("#" + id).length > 0) {
                id = GridsterUtil.randomInt(1000000, 9999999);
            }
            return id;
        },
        addContainer : function(sizeX, sizeY, dataCol, dataRow) {
////            var containerId = new Date().getTime();
//            var containerId = GridsterUtil.generateUniqueId();
//            // get position of new container/widget according to add to gridster
//            for (var row = dataRow; row <= GRIDSTER_MAX_ROWS; row++) {
//                for(var col = dataCol; col <= GRIDSTER_MAX_COLS; col++) {
//                    if (gridster.is_empty(col, row)) {
//                        gridster.add_widget("<li id=\"" + (containerId) 
//                              + "\" class='dashboard-block'></li>", sizeX, sizeY, col, row);
//                        GridsterUtil.addContainerMenu(containerId);
//                        return containerId;
//                    }   
//                }
//            }
            var containerId = GridsterUtil.generateUniqueId();
            gridster.add_widget("<li id=\"" + (containerId) 
                    + "\" class='dashboard-block'></li>", sizeX, sizeY, dataCol, dataRow);
//            GridsterUtil.addContainerMenu(containerId);
            return containerId;

        },
        getComponentByContainerId : function(containerId) {
            var retComponent = undefined;
            var components = listComponent;
            for(var i=0,n=components.length; i<n; i++) {
                var component = components[i];
                var containerIdTemp = component['containerId'];
                if(containerIdTemp == containerId) {
                    retComponent = component;
                    break;
                }
            }
            return retComponent;
        },
        getComponentByComponentId : function(componentId) {
            var retComponent = undefined;
            var components = listComponent;
            for(var i=0,n=components.length; i<n; i++) {
                var component = components[i];
                var componentIdTemp = component['componentId'];
                if(componentIdTemp === componentId) {
                    retComponent = component;
                    break;
                }
            }
            return retComponent;
        },
        addComponent : function(widget) {
            var dataCol = widget.dataCol;
            var dataRow = widget.dataRow;
            var dataSizeX = widget.dataSizeX;
            var dataSizeY = widget.dataSizeY;
            
            var type = widget.type;
            var config = widget.config;
           
            var containerId = GridsterUtil.addContainer(dataSizeX, dataSizeY, dataCol, dataRow);
            
//            var componentId = new Date().getTime();
            var componentId = GridsterUtil.generateUniqueId();
            var component = undefined;
            
            if(type === "Board01") {
//                var title = config.title || "";
                var title = "Board01";
                component = new Board01(containerId, componentId, title, componentId);
            } 
            if(component != undefined) {
                listComponent.push(component);
            }
            return component;
        },
        setVisibleComponentMenu : function(isVisible) {
            for (var i = 0; i < listComponent.length; i++) {
                var component = listComponent[i];
                var id = component['containerId'];
                var menuContainer = $("#" + id).find("#componentMenu");
                if(isVisible) {
                    menuContainer.addClass("menu-block");
                } else {
                    menuContainer.removeClass("menu-block");
                }
            }
        },
        setDisableDragging : function(isDisabled) {
            if(isDisabled === true) {
                gridster.disable();
            } else {
                gridster.enable();
            }
        },
        setDisabledResize : function(isDisabled) {
            if(isDisabled === true) {
                gridster.disable_resize();
            } else {
                gridster.enable_resize();
            }
        },
        getCurrentLiveViewData : function() {
            
            var elements = $('div.gridster ul').find('li');
            
            var data = [];
            
            var len = 0;
            if (elements != undefined && elements.length > 0) {
                len = elements.length;
            }
            
            for (var i = 0; i < len; i++) {
                
                var element = elements[i];
                
                var containerId = element.getAttribute('id');
                var dataRow = element.getAttribute('data-row');
                var dataCol = element.getAttribute('data-col');
                var dataSizeX = element.getAttribute('data-sizex');
                var dataSizeY = element.getAttribute('data-sizey');
                
                /** fixed draggable.stop event (when gridster not remove li) **/
                if ((null != dataCol) && (null != dataRow) 
                        && (null != dataSizeX) && (null != dataSizeY)
                        && (null != containerId)) {
                    
                    var jsonData = {};
                    jsonData['dataCol'] = dataCol;
                    jsonData['dataRow'] = dataRow;
                    jsonData['dataSizeX'] = dataSizeX;
                    jsonData['dataSizeY'] = dataSizeY;
                    for (var i = 0; i < listComponent.length; i++) {
                        var component = listComponent[i];
                        if (containerId == component.containerId) {
                            jsonData = component.getLiveViewCfg(jsonData);
                            break;
                        }
                    }
                    data.push(jsonData);
                }
            }
            return data;
        },
    };
}();


var initDashboard = function(json) {
    var widget = '' || {};
    widget['dataCol'] = '1';
    widget['dataRow'] = '1';
    widget['dataSizeX'] = '256';
    widget['dataSizeY'] = '256';
    widget['type'] = 'Board01';
    var component1 = GridsterUtil.addComponent(widget);
    component1.init();
//    var component2 = GridsterUtil.addComponent(widget);
//    component2.init();
//    var component3 = GridsterUtil.addComponent(widget);
//    component3.init();
};